﻿using System;
using Lin.Library.Web;
using Lin.Library.Extensions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.Security;
using System.Web;

namespace Lin.Website.Admin
{
    public partial class Login : BaseController
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var name = WebContext.GetString("name");
            if (name != string.Empty)
            {
                DoLogin(name);
            }
        }

        private void DoLogin(string name)
        {
            var json = new JObject();
            var pass = WebContext.GetString("pass");
            var code = WebContext.GetString("code");

            if (name == string.Empty)
            {
                json.Add("message", "用户名不能为空.");
            }
            else if (pass == string.Empty)
            {
                json.Add("message", "密码不能为空.");
            }
            else if (code == string.Empty)
            {
                json.Add("message", "验证码不能为空.");
            }
            else if (Session["LoginVerif"] == null)
            {
                json.Add("message", "验证码已失效,请刷新.");
            }
            else if (Session["LoginVerif"].ToString() != code)
            {
                json.Add("message", "验证码错误.");
            }
            else
            {
                //数据验证

                var user = BaseApi.Post(this.ApiAdress("LoginAuth"), JsonConvert.SerializeObject(new { name = name, pass = pass }));

                //访问API出错或数据库出错
                if (user == string.Empty)
                {
                    json.Add("message", "服务发生错误.");
                }
                else if (user == "null")
                {
                    //用户不存在或不允许登陆
                    json.Add("message", "用户名或密码错误.");
                }
                else
                {
                    json.Add("url", "/Admin/Index.aspx");

                    var ticket = new FormsAuthenticationTicket(name, false, 30);
                    var hasher = FormsAuthentication.Encrypt(ticket);
                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hasher);

                    if (ticket.IsPersistent)
                    {
                        cookie.Expires = ticket.Expiration;
                    }

                    Response.Cookies.Add(cookie);

                }
            }

            this.WriteJson(json.ToString());
        }
    }
}